import apiApp from '@/api/app'
import router from '@/router'
import useMenuStore from './menu'
import useRouteStore from './route'
import useSettingsStore from './settings'
import useTabbarStore from './tabbar'
import defAva from '@/assets/images/profile.jpg'
import { getToken, setToken, removeToken } from '@/utils/token'
import cache from '@/utils/cache'
import { func } from '@/utils/func'
import type { Menu } from '#/global'
import apiUser from '@/api/system/user'
const useUserStore = defineStore(
  // 唯一ID
  'user',
  () => {
    const settingsStore = useSettingsStore()
    const routeStore = useRouteStore()
    const menuStore = useMenuStore()
    const tabbarStore = useTabbarStore()

    const userinfo = ref(cache.local.getJSON("USERINFO") ?? {})

    const config: any = ref(cache.local.getJSON("EOACONFIG") ?? {})

    const roles = ref<string[]>([])
    const permissions = ref<string[]>([])


    const isLogin = computed(() => {
      if (getToken()) {
        return true
      }
      return false
    })

    // 登录
    async function login(data: any) {
      return new Promise((resolve, reject) => {
        apiApp.login(data).then(res => {
          setToken(res.data.access_token)
          resolve(res.data.access_token)
        }).catch((err) => {
          reject(err.response)
        })
      })
    }

    
    // 登录
    async function loginVerify(data: any) {
      return new Promise((resolve, reject) => {
        apiApp.loginVerify(data).then(res => {
          setToken(res.data.access_token)
          resolve(res.data.access_token)
        }).catch(() => {
          reject()
        })
      })
    }

    // 手动登出
    function logout(redirect = router.currentRoute.value.fullPath) {
      apiApp.logout().then(() => {
        // 此处仅清除计算属性 isLogin 中判断登录状态过期的变量，以保证在弹出登录窗口模式下页面展示依旧正常
        removeToken()
        router.push({
          name: 'login',
          query: {
            ...(redirect !== settingsStore.settings.home.fullPath && router.currentRoute.value.name !== 'login' && { redirect }),
          },
        }).then(logoutCleanStatus)
      })
    }
    // 请求登出
    function requestLogout() {
      // 此处仅清除计算属性 isLogin 中判断登录状态过期的变量，以保证在弹出登录窗口模式下页面展示依旧正常
      removeToken()
      router.push({
        name: 'login',
        query: {
          ...(
            router.currentRoute.value.fullPath !== settingsStore.settings.home.fullPath
            && router.currentRoute.value.name !== 'login'
            && {
              redirect: router.currentRoute.value.fullPath,
            }
          ),
        },
      }).then(logoutCleanStatus)
    }
    // 登出后清除状态
    function logoutCleanStatus() {
      cache.local.remove("USERINFO")
      userinfo.value = {}
      roles.value = []
      permissions.value = []
      settingsStore.updateSettings({}, true)
      tabbarStore.clean()
      routeStore.removeRoutes()
      menuStore.setActived(0)
    }

    // 获取权限
    async function getPermissions() {
          await apiApp.getPermission().then((res: any) => {
            permissions.value = res.data
          })
    }

    // 修改密码
    async function editPassword(data: {
      oldPassword: string
      newPassword: string
    }) {
      await apiUser.updateUserPwd(data)
    }

    async function getRouters() {
      // console.log('---------------------------getRouters')
      return new Promise((resolve, reject) => {
        apiApp.getRouters().then((res) => {
          resolve((res.data as Menu.recordMainRaw[]).filter(item => item.children.length !== 0))
        }).catch((error: any) => {
          reject(error)
        })
      })
    }
    async function getConfig() {
      await apiApp.allConfig().then(res => {
        const rows = res.data
        var conf: any = {}
        for (let i = 0; i < rows.length; i++) {
          var ckey = rows[i].confKey.split(".")
          if (ckey.length == 2) {
            if (conf[ckey[0]] === undefined) {
              conf[ckey[0]] = {}
            }
            conf[ckey[0]][ckey[1]] = rows[i].confValue
          } else if (ckey.length == 3) {
            if (conf[ckey[0]] === undefined) {
              conf[ckey[0]] = {}
            }
            if (conf[ckey[0]][ckey[1]] === undefined) {
              conf[ckey[0]][ckey[1]] = {}
            }
            conf[ckey[0]][ckey[1]][ckey[2]] = rows[i].confValue
          } else {
            conf[rows[i].confKey] = rows[i].confValue
          }
        }
        config.value = conf
        cache.local.setJSON("EOACONFIG", conf)
      })
    }

    // 获取权限
    async function getInfo() {
      await apiApp.getInfo().then((res: any) => {
        const user = res.data.user
        if (user.avatar == null || user.avatar == "") {
          user.avatar = defAva
        } else{
          user.avatar =ossUrl(user.avatar);
        }
        if (res.data.roles && res.data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
          roles.value = res.data.roles
        } else {
          roles.value = ['ROLE_DEFAULT']
        }
        userinfo.value = user
        cache.local.setJSON("USERINFO", userinfo.value)
      })
    }

    function ossUrl(url: string) {
      // 处理空值情况
      if (func.isBlank(url)) {
        return '';
      }
      
      // 检查是否已包含协议
      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url;
      }
      
      // 确保ossBaseUrl存在且格式正确
      const baseUrl = config.value?.sys?.ossBaseUrl;
      if (func.isBlank(baseUrl)) {
        console.warn('OSS基础URL未配置，使用原始URL');
        return url;
      }
      
      // 确保URL拼接时不会出现多余的斜杠
      const normalizedBaseUrl = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
      const normalizedUrl = url.startsWith('/') ? url.slice(1) : url;
      
      return `${normalizedBaseUrl}/${normalizedUrl}`;
    }

    return {
      userinfo,
      config,
      roles,
      permissions,
      isLogin,
      login,
      loginVerify,
      logout,
      requestLogout,
      getPermissions,
      editPassword,
      getConfig,
      getInfo,
      getRouters,
      ossUrl
    }
  },
)

export default useUserStore
